#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from assoce.core.models import *
from assoce.bibli.models import *
from datetime import datetime

import csv

def parseDate(strdate):
    if len(strdate)==0: return None
    d, m, y = strdate.split('/')
    return datetime(int(y), int(m), int(d))

def utf8(s):
    return s.decode('latin-1').encode('utf-8')

Livre.objects.all().delete()
Item.objects.all().delete()
bd = Activite.objects.get_or_create(label='BD')[0]
compte = bd.compte_set.all()[0]
regl = Operation.objects.get_or_create(compte=compte, value=0.0)[0]

f=open("bd1.csv", "rb")
reader = csv.reader(f)
reader.dialect.delimiter = ';'
for row in list(reader):
    if not row[0] or row[0]=='': continue
    if len(row[1])==0 and len(row[2])==0: continue
    serie = Serie.objects.get_or_create(label=utf8(row[1]))[0]
    auteur = Auteur.objects.get_or_create(label=utf8(row[4]))[0]
    ed = Editeur.objects.get_or_create(label=utf8(row[5]))[0]
    print row[6]
    date = parseDate(row[6])
    
    item = Item(date=date, label=utf8(row[3]), activite=bd, achat=regl)
    item.save()
    l = Livre(item=item, ref=row[0], editeur=ed, auteur=auteur, serie=serie)
    if len(row[2])>0:
        try:
            tome=int(row[2])
            l.tome = tome
        except Exception, v:
            pass
    l.save()
